console.log('content script start')

// inject injected script
var s = document.createElement('script')
s.src = chrome.runtime.getURL('injected.js')
s.onload = function() {
  this.remove()
};
(document.head || document.documentElement).appendChild(s)
let data = []
let init = false
// 从后台脚本获取酒店配置
let myMap = new Map()

// 初始化配置
async function initializeConfig() {
  try {
    // 发送消息给background脚本从Gitee获取配置
    const response = await chrome.runtime.sendMessage({action: 'fetchFromGitee'})
    console.log('加载response',JSON.stringify(response))
    if (response && response.success && response.config) {
      // 将配置转换为Map格式
      myMap.clear()
      for (const [hotelName, template] of Object.entries(response.config)) {
        myMap.set(hotelName, template)
      }
      console.log('从Gitee获取酒店配置成功，共加载了', myMap.size, '个酒店配置')
    } else {
      console.log('无法从Gitee获取配置，使用默认配置:', response?.error)
      loadDefaultConfig()
    }
  } catch (error) {
    console.log('获取配置失败，使用默认配置:', error)
    loadDefaultConfig()
  }
}

// 加载默认配置（作为备用）
function loadDefaultConfig() {
  myMap.clear()
  myMap.set('常州环球港邮轮酒店', '${userName}  ${roomType}-${mealType} ${startDate}  ${roomNum}${nightNum}  晨风旅行社 房价0   房费预付，杂费自理，房价保密')
  myMap.set('常州远洲酒店', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  ')
  myMap.set('茅山南湖度假庄园', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  ')
  myMap.set('徐州吕梁水街开元颐居度假酒店', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  0')
  myMap.set('常州沁悦大酒店（湖塘纺织城店）', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  0')
  myMap.set('常州宝丽格大酒店', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  0')
  myMap.set('无锡鲁能万豪酒店', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  ')
  myMap.set('常州富都洲际酒店', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  0')
  myMap.set('常州万泽酒店（武进春秋淹城店）', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  0')
  myMap.set('维也纳国际酒店（东莞松山湖店）', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  维也纳国际酒店（东莞松山湖店）')
  myMap.set('茗静园·安吉禧玥山居度假酒店', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  茗静园·安吉禧玥山居度假酒店')
  myMap.set('常州富力万达嘉华酒店', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  常州富力万达嘉华酒店')
  myMap.set('壹宿酒店（滨江万达店）', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  壹宿酒店（滨江万达店）')
  myMap.set('建湖九龙国际大酒店', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}   ${channel}')
  myMap.set('南京国际会议大酒店', '客人：${userName}</br>入住：${startDate}</br>离店：${endDate}</br>房型：${roomType}</br>早餐：${mealType}</br>间数： ${roomNum}</br>金额：0</br>渠道：${channel}')
  myMap.set('常州都喜天丽富都龙城酒店', '${userName}  ${roomType} <${mealType}>  ${startDate}  ${roomNum}${nightNum}  ${channel} 0 ')
  myMap.set('茅山道温泉度假酒店', '预订信息</br>预订日期:${startDate}</br>预订业务员:美团合作</br>预订人:${userName}</br>预订房型:${roomType}</br>房间数量:${roomNum}${nightNum}</br>房费:0/间</br>备注:')
  myMap.set('瑞颐康养酒店', '酒店名 : 苏州瑞颐康养酒店</br>入离日期 : ${startDate}~${endDate}  共${nightNum}</br>客人姓名 :  ${userName}</br>预订房型 : ${roomType}-${roomNum} ${mealType}               </br>结算价：0')
  myMap.set('常州富都戴斯酒店', '店名 : 常州富都戴斯酒店</br>入离日期 :${startDate}至${endDate}共${nightNum}</br>客人姓名：${userName}</br>预订房型: ${roomType}房  ${mealType} ${roomNum}</br>结算价：0</br>来源：${channel}</br>备注：该客人房费已支付，本公司统一结算。房价保密，杂费自理。</br>发票：本公司开具。</br>烦请确认回复，谢谢')
  myMap.set('建德航空小镇君澜度假酒店', '酒店名 : 建德航空小镇君澜度假酒店</br>入离日期 : ${startDate}至${endDate}共${nightNum}</br>客人姓名 :  ${userName}</br>预订房型 : ${roomType}房+${mealType}  ${roomNum}</br>结算：00')
  myMap.set('广州百花山庄度假村（增城万达广场店）', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  广州百花山庄度假村（增城万达广场店）')
  myMap.set('溧阳水西·天目湖酒店', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum} 0 ')
  myMap.set('南宁荣荣大酒店（江南万达店）', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  南宁荣荣大酒店（江南万达店）')
  myMap.set('艺龙瑞云酒店（河源万隆城喷泉店）', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum} 0 美团')
  myMap.set('德鸿汇金酒店（龙岩动车站店）', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  售卖价 0 ')
  myMap.set('润元酒店（龙岩万宝广场店）', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  售卖价 0 ')
  myMap.set('德鸿兴大洋SMART智能酒店（龙岩站店）', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  售卖价 0 ')
  myMap.set('星辰智能投影酒店（龙岩万宝广场店）', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  售卖价 0 ')
  myMap.set('达曼酒店', '酒店名 :达曼酒店</br> 入离日期 : ${startDate}至${endDate}共${nightNum}</br> 客人姓名 : ${userName}</br> 预订房型 : ${roomType}<${mealType}>- ${roomNum}</br> 结算:0</br> 渠道:美团  ')
  myMap.set('德鸿万阳酒店', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}  售卖价 0 ')
  myMap.set('维也纳酒店（金坛四中八佰伴店）', '${userName}  ${roomType}-${mealType}  ${startDate}  ${roomNum}${nightNum}  美团 0 ')
  myMap.set('逸米s酒店（杭州千岛湖景区店）', '${userName}  ${roomType}-${mealType}  ${startDate}  ${roomNum}${nightNum}  逸米s酒店（杭州千岛湖景区店）')
  myMap.set('常州迷霖套房酒店（中华恐龙园店）', '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum} ')
  myMap.set('常州金色云庭国际酒店', '${userName}  ${roomType}-${mealType}  ${startDate}  ${roomNum}${nightNum} 0')
  myMap.set('常州金色云庭国际酒店', '${userName}  ${roomType}-${mealType}  ${startDate}  ${roomNum}${nightNum} 000')
  myMap.set("艺龙瑞云酒店（河源亚洲第一高喷泉店）", '${userName}  ${roomType}<${mealType}> ${startDate}  ${roomNum}${nightNum}  000 ${channel}');
  myMap.set("石家庄长安万达美华轻尚酒店", '${userName}  ${roomType}-${mealType} ${startDate}  ${roomNum}${nightNum}  ${channel} 000');
  myMap.set("苏州雍景山庄", '${userName}  ${roomType} ${mealType}  ${startDate}  ${roomNum}${nightNum}');
  myMap.set("常州迷霖套房酒店（中华恐龙园店）", '${userName}  ${roomType} ${mealType} ${startDate}  ${roomNum}${nightNum}');
  myMap.set("常州经开区福朋喜来登酒店", '公司：常州方向标网络科技有限公司</br>姓名：${userName}</br>入住日期:${startDate}</br>离店日期:${endDate}</br>房型:  ${roomType}</br>房价：000 ${mealType}</br>房间数：${roomNum}</br>付款方式：退房联系销售</br>确认号：');
  myMap.set("苏州清山会议中心", '${userName}  ${roomType}-${mealType}  ${startDate}  ${roomNum}${nightNum}  券号：');
}

// 页面加载时初始化配置
if(!init){
  init = true
  initializeConfig()
}


var customDiv = null;
window.addEventListener('message',
  function(e) {
    const url = e.data.url;
    const orgin = window.location.orgin;
    /* if(!orgin){
     return
     }
     if(orgin.indexOf('me.meituan.com')<0 || url.indexOf("orders")<0){*/
    if (!url || (url.indexOf('orders') < 0 && url.indexOf('userInfo') < 0&& url.indexOf('order/task') < 0)) {
      return
    }
    if (url.indexOf('order/task') > -1||url.indexOf('orders') > -1) {
      data = [];
      let arr = JSON.parse(e.data.data).data.data
      if(!arr){
        arr = []
      }
      arr.forEach(function(row) {
        const userNames = row.guests.map(g => g.name).join(',');
        data.push({
          orderId: row.orderId,
          poiName: row.poiName,
          userName: userNames,
          startDate: row.checkIn,
          endDate: row.checkOut,
          roomType: getRoomType(row.roomName),
          mealType: getMealType(row.rpInfo.breakfastDesc),
          roomNum: row.roomCount + '间',
          nightNum: row.days + '晚',
          channel: '美团'
        })
      })
    } else if (url.indexOf('userInfo') > -1) {
      const name = JSON.parse(e.data.data).data.guests[0].name
      const regex = /(\d{19})/
      const match = url.match(regex)
      if (match) {
        const row = data.find(item => item.orderId === match[0])
        row.userName = name
      }
      renderDivs(data, myMap, customDiv)
      return
    }
    var buttons = document.querySelectorAll('button.my-button-class')
    console.log("按钮的数量",buttons.length)
    if (buttons.length == 0) {
      // 创建按钮
      var button = document.createElement('button')
      button.textContent = '打开弹框'
      button.style.position = 'fixed'
      button.style.top = '10px'
      button.style.left = '10px'
      button.style.zIndex = '999999999'
      button.style.padding = '10px'
      button.style.fontSize = '14px'
      button.style.backgroundColor = '#007BFF'
      button.style.color = 'white'
      button.style.border = 'none'
      button.style.borderRadius = '5px'
      button.style.cursor = 'pointer'
      button.classList.add('my-button-class')
      document.body.appendChild(button)

      // 创建刷新配置按钮
      var refreshButton = document.createElement('button')
      refreshButton.textContent = '刷新配置'
      refreshButton.style.position = 'fixed'
      refreshButton.style.top = '10px'
      refreshButton.style.left = '120px'
      refreshButton.style.zIndex = '999999999'
      refreshButton.style.padding = '10px'
      refreshButton.style.fontSize = '14px'
      refreshButton.style.backgroundColor = '#28a745'
      refreshButton.style.color = 'white'
      refreshButton.style.border = 'none'
      refreshButton.style.borderRadius = '5px'
      refreshButton.style.cursor = 'pointer'
      refreshButton.classList.add('refresh-button-class')
      document.body.appendChild(refreshButton)

      // 为刷新按钮添加点击事件
      refreshButton.addEventListener('click', async function() {
        console.log('手动刷新配置');
        refreshButton.textContent = '刷新中...';
        refreshButton.disabled = true;

        try {
          await initializeConfig(true); // 强制刷新配置
          refreshButton.textContent = '刷新成功';
          refreshButton.style.backgroundColor = '#28a745';

          // 2秒后恢复按钮状态
          setTimeout(() => {
            refreshButton.textContent = '刷新配置';
            refreshButton.disabled = false;
          }, 2000);
        } catch (error) {
          console.error('刷新配置失败:', error);
          refreshButton.textContent = '刷新失败';
          refreshButton.style.backgroundColor = '#dc3545';

          // 2秒后恢复按钮状态
          setTimeout(() => {
            refreshButton.textContent = '刷新配置';
            refreshButton.style.backgroundColor = '#28a745';
            refreshButton.disabled = false;
          }, 2000);
        }
      });
      // 创建自定义 div
      customDiv = document.createElement('div')
      customDiv.style.display = 'none' // 初始时隐藏
      customDiv.style.overflow = 'auto'
      customDiv.style.position = 'fixed'
      customDiv.style.top = '50px'
      customDiv.style.left = '10px'
      customDiv.style.width = '450px'
      customDiv.style.padding = '20px'
      customDiv.style.backgroundColor = 'white' // 设置为白色
      customDiv.style.color = 'black'
      customDiv.style.borderRadius = '8px'
      customDiv.style.boxShadow = '0px 4px 8px rgba(0, 0, 0, 0.2)'
      customDiv.style.zIndex = '999999999999'
      customDiv.style.fontFamily = 'SimSun, 宋体, serif' // 设置字体为宋体
      customDiv.style.fontSize = '13px' // 设置字体大小为 11px
      customDiv.style.height = '90vh'
      document.body.appendChild(customDiv)
      // 为按钮添加点击事件
      button.addEventListener('click',
        function() {
          if (customDiv.style.display === 'none') {
            renderDivs(data, myMap, customDiv)
            customDiv.style.display = 'block' // 如果 hidden，则显示 customDiv
          } else {
            customDiv.style.display = 'none' // 如果 visible，则隐藏 customDiv
          }
        })
    }
    //console.log('content script received:', e.data.data);
  })

function getMealType(mealType) {
  if(mealType=='2份早餐'){
    return "双早"
  } else if(mealType=='1份早餐'){
    return "单早"
  }
  return mealType;
}
function renderDivs(data, myMap, customDiv) {
  // 删除 customDiv 中所有 class 为 'my-div-son' 的 div
  var sonDivs = customDiv.querySelectorAll('.my-div-son') // 获取所有 class 为 'my-div-son' 的 div
  sonDivs.forEach(function(div) {
    div.remove() // 删除每个 div
  })
  let i = 0
  data.forEach(function(div, index) {
    const string = myMap.get(div.poiName)
    if (!string) {
      return
    }
    i++;
    const result = string.replace('${userName}', div.userName)
      .replace('${roomType}', div.roomType)
      .replace('${mealType}', div.mealType)
      .replace('${startDate}', div.startDate)
      .replace('${endDate}', div.endDate)
      .replace('${roomNum}', div.roomNum)
      .replace('${nightNum}', div.nightNum)
      .replace('${channel}', div.channel)
    var div1 = document.createElement('div')
    if (i % 2 == 0) {
      div1.style.backgroundColor = 'lightgray'
    }
    //div1.innerHTML  = div.poiName+"      "+result; // 给第一个 div 添加文本内容
    div1.innerHTML = result // 给第一个 div 添加文本内容
    div1.classList.add('my-div-son')
    div1.style.marginBottom = '10px' // 给第一个 div 设置底部外边距
    customDiv.appendChild(div1)
    div1.addEventListener('click', function() {
      // 创建一个范围对象
      var range = document.createRange()
      range.selectNodeContents(div1)
      // 获取当前选择对象
      var selection = window.getSelection()
      selection.removeAllRanges()  // 清除任何现有的选择
      selection.addRange(range)    // 添加新的选择范围
    })
  })
}



 function getRoomType(inputString) {
     // console.log('roomType',inputString)
    const roomRegex = /(.+?[房间屋])([ABCDE])?/;  // 匹配房型（如“豪华双人房”或“豪华大床间”）
    const roomMatch = inputString.match(roomRegex);  // 匹配房型

    return roomMatch ? roomMatch[1] : '';  // 如果匹配到，返回房型；否则返回空字符串
}
